//
//  JSQPushMessageManager.m
//  Conversation
//
//  Created by C_HAO on 15/10/13.
//  Copyright © 2015年 CHAOO. All rights reserved.
//

#import "JSQPushMessageManager.h"
#import "JSQMessageTools.h"

@implementation JSQPushMessageManager

+ (void)startGetMessageURL:(NSURL *)URL parameter:(NSDictionary *)parameter complete:(void (^)(MessageClass type, NSDictionary *message, BOOL over, NSString *ACK))complete {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        [request setHTTPMethod:@"POST"];

        NSData *data = [[JSQPushMessageManager stringWithDictionary:parameter] dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];

        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

        NSURLSession *_URLSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:[NSOperationQueue mainQueue]];

        __block NSData *received;
        NSURLSessionDataTask *sessionDataTask = [_URLSession dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
            received = data;
            dispatch_semaphore_signal(semaphore);
        }];

        [sessionDataTask resume];

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

        [JSQPushMessageManager analysisNewsMessage:received complete:complete];
    });
}

+ (void)startAcquireMessageURL:(NSURL *)URL parameter:(NSDictionary *)parameter complete:(void (^)(NSData *consequence))complete;
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        [request setHTTPMethod:@"POST"];
        NSData *data = [[JSQPushMessageManager stringWithDictionary:parameter] dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];

        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

        NSURLSession *_URLSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:[NSOperationQueue mainQueue]];

        __block NSData *received;
        NSURLSessionDataTask *sessionDataTask = [_URLSession dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
            received = data;
            dispatch_semaphore_signal(semaphore);
        }];

        [sessionDataTask resume];

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

        if (complete) {
            complete(received);
        }
    });
}

+ (NSString *)stringWithDictionary:(NSDictionary *)dictionary {
    NSString *string = [NSString string];
    if (!dictionary || dictionary.count == 0) {
        return string;
    }
    for (NSString *key in dictionary.allKeys) {
        NSString *valueStr = [NSString string];
        id value = [dictionary objectForKey:key];

        if ([value isKindOfClass:[NSString class]]) {
            valueStr = (NSString *)value;
        } else if ([value isKindOfClass:[NSNumber class]]) {
            valueStr = [(NSNumber *) value stringValue];
        }

        string = [[[(string.length) ? string : @"&" stringByAppendingString:key] stringByAppendingString:@"="] stringByAppendingString:valueStr];

    }
    return string;
}

+ (NSDictionary *)analysis:(NSString *)string {
    if (!string) {
        return nil;
    }
    NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
    if (err) {
        return nil;
    }
    return jsonDic;
}

+ (void)analysisNewsMessage:(NSData *)messageData complete:(void (^)(MessageClass type, NSDictionary *message, BOOL over, NSString *ACK))complete {
    NSString *messageStr = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];
    NSArray *valueArray = [messageStr componentsSeparatedByString:@"\n"];

    NSString *msgIndex;
    for (NSString *keyValue in valueArray) {
        NSArray *valueArray = [keyValue componentsSeparatedByString:@"="];
        if (valueArray != nil && [valueArray count] == 2) {
            NSString *msg = [valueArray firstObject];
            NSString *value = [valueArray lastObject];
            if ([msg isEqualToString:@"msg"]) {
                NSRange rangFirstComma = [value rangeOfString:@","];
                if (rangFirstComma.length <= 0) {
                    continue;
                }
                NSRange rangSecondComma = [value rangeOfString:@",{"];
                if (rangSecondComma.length <= 0) {
                    continue;
                }
                msgIndex = [value substringToIndex:rangFirstComma.location];

                NSString *key = [value substringWithRange:NSMakeRange(rangFirstComma.location + 1, rangSecondComma.location - rangFirstComma.location - 1)];

                NSString *content = [value substringFromIndex:(rangSecondComma.length + rangSecondComma.location - 1)];

                NSDictionary *jsonResult = [JSQPushMessageManager analysis:content];

                if ([key isEqualToString:[JSQMessageTools enumToString:MessagePMS]]) {
                    if (complete) complete(MessagePMS, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageIYM]]) {
                    if (complete) complete(MessageIYM, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageMMS]]) {
                    if (complete) complete(MessageMMS, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageJMG]]) {
                    if (complete) complete(MessageJMG, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageLMG]]) {
                    if (complete) complete(MessageLMG, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageMMG]]) {
                    if (complete) complete(MessageMMG, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageACC]]) {
                    if (complete) complete(MessageACC, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageADC]]) {
                    if (complete) complete(MessageADC, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageWAF]]) {
                    if (complete) complete(MessageWAF, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageCAF]]) {
                    if (complete) complete(MessageCAF, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDLF]]) {
                    if (complete) complete(MessageDLF, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDLT]]) {
                    if (complete) complete(MessageDLT, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDLD]]) {
                    if (complete) complete(MessageDLD, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageAMS]]) {
                    if (complete) complete(MessageAMS, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageJGI]]) {
                    if (complete) complete(MessageJGI, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageCJG]]) {
                    if (complete) complete(MessageCJG, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageCNM]]) {
                    if (complete) complete(MessageCNM, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageSBM]]) {
                    if (complete) complete(MessageSBM, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageFAH]]) {
                    if (complete) complete(MessageFAH, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageSOM]]) {
                    if (complete) complete(MessageSOM, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDDM]]) {
                    if (complete) complete(MessageDDM, jsonResult, NO, msgIndex);
                } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageRSC]]) {
                    if (complete) complete(MessageRSC, jsonResult, NO, msgIndex);
                }
            }
        }

    }
    if (complete) complete(MessageNOR, nil, YES, msgIndex);
}

+ (void)analysisNews:(NSDictionary *)messageDictionary complete:(void (^)(MessageClass type, NSString *ACK))complete {
    if (!messageDictionary) {
        return;
    }

    NSString *msgIndex = [messageDictionary objectForKey:@"id"];
    NSString *key = [messageDictionary objectForKey:@"type"];

    if ([key isEqualToString:[JSQMessageTools enumToString:MessagePMS]]) {
        if (complete) complete(MessagePMS, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageIYM]]) {
        if (complete) complete(MessageIYM, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageMMS]]) {
        if (complete) complete(MessageMMS, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageJMG]]) {
        if (complete) complete(MessageJMG, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageLMG]]) {
        if (complete) complete(MessageLMG, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageMMG]]) {
        if (complete) complete(MessageMMG, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageACC]]) {
        if (complete) complete(MessageACC, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageADC]]) {
        if (complete) complete(MessageADC, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageWAF]]) {
        if (complete) complete(MessageWAF, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageCAF]]) {
        if (complete) complete(MessageCAF, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDLF]]) {
        if (complete) complete(MessageDLF, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDLT]]) {
        if (complete) complete(MessageDLT, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDLD]]) {
        if (complete) complete(MessageDLD, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageAMS]]) {
        if (complete) complete(MessageAMS, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageJGI]]) {
        if (complete) complete(MessageJGI, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageCJG]]) {
        if (complete) complete(MessageCJG, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageCNM]]) {
        if (complete) complete(MessageCNM, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageSBM]]) {
        if (complete) complete(MessageSBM, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageFAH]]) {
        if (complete) complete(MessageFAH, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageSOM]]) {
        if (complete) complete(MessageSOM, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageDDM]]) {
        if (complete) complete(MessageDDM, msgIndex);
    } else if ([key isEqualToString:[JSQMessageTools enumToString:MessageRSC]]) {
        if (complete) complete(MessageRSC, msgIndex);
    }
}

+ (NSDictionary *)analysisData:(NSData *)data
{
    if (!data) {
        return nil;
    }
    
    NSError *err;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
    
    if (err) {
        return nil;
    }
    
    
    return json;
}


@end
